<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Services;

class ClientUserService
{
    protected $userFdBind = []; // user_id => fd

    protected $fdUserBind = []; // fd => user_id

    protected $userRommBind = []; // user_id => room_id

    private static $instancs = null;

    private function __construct()
    {
    }

    private function __clone()
    {
        // TODO: Implement __clone() method.
    }

    public static function getInstance()
    {
        if (! self::$instancs instanceof self) {
            self::$instancs = new self();
        }
        return self::$instancs;
    }

    public function bind($userId, $fd): void
    {
        $this->userFdBind[$userId] = $fd;
        $this->fdUserBind[$fd] = $userId;
    }

    public function unbind($fd): void
    {
        $userId = $this->getUserIdByFd($fd);
        // 只有在用户主动退出了房间后 才能删掉 userRommBind
        // 意外断线这个要留着 再次链接时候把用户带进去
        unset($this->fdUserBind[$fd], $this->userFdBind[$userId], $this->userRommBind[$userId]);
    }

    public function getFdByUserId($userId): int
    {
        return $this->userFdBind[$userId] ?? 0;
    }

    public function getUserIdByFd($fd): int
    {
        return $this->fdUserBind[$fd] ?? 0;
    }

    public function checkBind($userId): bool
    {
        return isset($this->userFdBind[$userId]);
    }

    public function getAllFds()
    {
        return array_keys($this->fdUserBind);
    }

    public function getAllUsers()
    {
        return array_keys($this->userFdBind);
    }
}
